<template>
  <div class="user-management-container">
    <div class="page-header">
      <h2 class="page-title">用户管理</h2>
      <div class="page-tools">
        <el-button type="primary" round :icon="Plus" @click="handleAdd">添加用户</el-button>
      </div>
    </div>

    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="queryParams" inline>
        <el-form-item label="用户名">
          <el-input v-model.trim="queryParams.username" placeholder="请输入用户名" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model.trim="queryParams.nickname" placeholder="请输入昵称" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select 
            v-model="queryParams.roleCode" 
            placeholder="请选择角色" 
            clearable 
            @change="handleRoleSelectChange"
            style="width: 150px;"
          >
            <el-option v-for="role in roleOptions" :key="role" :label="getRoleName(role)" :value="role" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="queryParams.status" 
            placeholder="请选择状态" 
            clearable 
            @change="handleStatusSelectChange"
            style="width: 150px;"
          >
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" round :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button round :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 用户表格 -->
    <el-card class="table-card" :body-style="{ padding: '20px' }" shadow="hover">
      <el-table
        v-loading="loading"
        :data="userList"
        border
        stripe
        style="width: 100%"
        row-key="id"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="nickname" label="昵称" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="phone" label="手机号" min-width="120" />
        <el-table-column prop="roleName" label="角色" min-width="100" />
        <el-table-column label="状态" min-width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" effect="light" round>
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="最后登录时间" min-width="180" align="center">
          <template #default="scope">
            {{ scope.row.lastLoginTime ? formatDateTime(scope.row.lastLoginTime) : '未登录' }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="180" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="280" align="center">
          <template #default="scope">
            <el-button type="primary" link :icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="primary" link :icon="Key" @click="handleResetPassword(scope.row)">重置密码</el-button>
            <el-button type="primary" link :icon="SwitchButton" @click="handleToggleStatus(scope.row)">
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="primary" link :icon="UserFilled" @click="handleRoleChange(scope.row)">角色变更</el-button>
            <el-button type="danger" link :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      destroy-on-close
      center
      append-to-body
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="用户名" prop="username" v-if="dialog.type === 'add'">
          <el-input v-model="userForm.username" placeholder="请输入用户名" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialog.type === 'add'">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" maxlength="20" show-password />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userForm.gender">
            <el-radio :label="0">未知</el-radio>
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色" prop="roleCode" v-if="dialog.type === 'add'">
          <el-select v-model="userForm.roleCode" placeholder="请选择角色">
            <el-option v-for="role in roleOptions" :key="role" :label="getRoleName(role)" :value="role" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button round @click="cancelForm">取 消</el-button>
          <el-button type="primary" round @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="resetPwdDialog.visible"
      title="重置密码"
      width="400px"
      destroy-on-close
      center
      append-to-body
    >
      <el-form
        ref="resetPwdFormRef"
        :model="resetPwdForm"
        :rules="resetPwdFormRules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetPwdForm.newPassword" type="password" placeholder="请输入新密码" maxlength="20" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button round @click="resetPwdDialog.visible = false">取 消</el-button>
          <el-button type="primary" round @click="submitResetPwd">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 角色变更对话框 -->
    <el-dialog
      v-model="roleDialog.visible"
      title="角色变更"
      width="400px"
      destroy-on-close
      center
      append-to-body
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleFormRules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="当前角色">
          <el-tag effect="plain">{{ getRoleName(roleDialog.currentRole) }}</el-tag>
        </el-form-item>
        <el-form-item label="新角色" prop="roleCode">
          <el-select v-model="roleForm.roleCode" placeholder="请选择新角色">
            <el-option v-for="role in roleOptions" :key="role" :label="getRoleName(role)" :value="role" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button round @click="roleDialog.visible = false">取 消</el-button>
          <el-button type="primary" round @click="submitRoleChange">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getUserList, getAllowedRoles, addUser, updateUser, 
  updateUserPassword, updateUserRole, updateUserStatus, deleteUser 
} from '@/api/admin'
import { 
  Edit, Delete, Plus, Search, Refresh, Key, UserFilled, SwitchButton 
} from '@element-plus/icons-vue'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  username: '',
  nickname: '',
  roleCode: '',
  status: undefined
})

// 表格数据
const loading = ref(false)
const userList = ref([])
const total = ref(0)

// 角色选项
const roleOptions = ref([])

// 用户表单对话框
const dialog = reactive({
  visible: false,
  title: '',
  type: 'add'
})

// 用户表单
const userFormRef = ref(null)
const userForm = reactive({
  id: undefined,
  username: '',
  password: '',
  nickname: '',
  email: '',
  phone: '',
  gender: 0,
  roleCode: '',
  status: 1
})

// 表单校验规则
const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '用户名长度必须在4-20个字符之间', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20个字符之间', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { max: 50, message: '昵称长度不能超过50个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  roleCode: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 重置密码对话框
const resetPwdDialog = reactive({
  visible: false,
  userId: undefined
})

// 重置密码表单
const resetPwdFormRef = ref(null)
const resetPwdForm = reactive({
  id: undefined,
  newPassword: ''
})

// 重置密码表单校验规则
const resetPwdFormRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20个字符之间', trigger: 'blur' }
  ]
}

// 角色变更对话框
const roleDialog = reactive({
  visible: false,
  userId: undefined,
  currentRole: ''
})

// 角色变更表单
const roleFormRef = ref(null)
const roleForm = reactive({
  id: undefined,
  roleCode: ''
})

// 角色变更表单校验规则
const roleFormRules = {
  roleCode: [
    { required: true, message: '请选择新角色', trigger: 'change' }
  ]
}

// 获取角色名称
const getRoleName = (roleCode) => {
  switch (roleCode) {
    case 'ADMIN':
      return '管理员'
    case 'INITIATOR':
      return '发起人'
    case 'CONTESTANT':
      return '参赛者'
    default:
      return roleCode
  }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(/\//g, '-')
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    // 准备请求参数，移除undefined的值
    const params = { ...queryParams }
    Object.keys(params).forEach(key => {
      if (params[key] === undefined) {
        delete params[key]
      }
    })
    
    const res = await getUserList(params)
    userList.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    console.error('获取用户列表失败', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    const res = await getAllowedRoles()
    roleOptions.value = res.data
  } catch (error) {
    console.error('获取角色列表失败', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  fetchUserList()
}

// 下拉选择框change事件处理
const handleRoleSelectChange = (value) => {
  queryParams.roleCode = value || ''
}

const handleStatusSelectChange = (value) => {
  // 确保status的值为数字或undefined
  queryParams.status = value === '' || value === null ? undefined : Number(value)
}

// 重置搜索
const resetQuery = () => {
  queryParams.username = ''
  queryParams.nickname = ''
  queryParams.roleCode = ''
  queryParams.status = undefined
  handleSearch()
}

// 添加用户
const handleAdd = () => {
  dialog.visible = true
  dialog.title = '添加用户'
  dialog.type = 'add'
  resetForm()
}

// 编辑用户
const handleEdit = (row) => {
  dialog.visible = true
  dialog.title = '编辑用户'
  dialog.type = 'edit'
  resetForm()
  Object.assign(userForm, { 
    id: row.id,
    nickname: row.nickname,
    email: row.email,
    phone: row.phone,
    gender: row.gender || 0,
    status: row.status
  })
}

// 重置表单
const resetForm = () => {
  userForm.id = undefined
  userForm.username = ''
  userForm.password = ''
  userForm.nickname = ''
  userForm.email = ''
  userForm.phone = ''
  userForm.gender = 0
  userForm.roleCode = ''
  userForm.status = 1
}

// 取消表单
const cancelForm = () => {
  dialog.visible = false
  resetForm()
}

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    
    if (dialog.type === 'add') {
      // 添加用户
      await addUser(userForm)
      ElMessage.success('添加用户成功')
    } else {
      // 编辑用户
      await updateUser(userForm)
      ElMessage.success('更新用户成功')
    }
    
    dialog.visible = false
    fetchUserList()
  } catch (error) {
    console.error('提交表单失败', error)
  }
}

// 重置密码
const handleResetPassword = (row) => {
  resetPwdDialog.visible = true
  resetPwdDialog.userId = row.id
  resetPwdForm.id = row.id
  resetPwdForm.newPassword = ''
}

// 提交重置密码
const submitResetPwd = async () => {
  if (!resetPwdFormRef.value) return
  
  try {
    await resetPwdFormRef.value.validate()
    
    await updateUserPassword(resetPwdForm)
    ElMessage.success('重置密码成功')
    
    resetPwdDialog.visible = false
  } catch (error) {
    console.error('重置密码失败', error)
  }
}

// 切换用户状态
const handleToggleStatus = (row) => {
  const status = row.status === 1 ? 0 : 1
  const statusText = status === 1 ? '启用' : '禁用'
  
  ElMessageBox.confirm(`确定要${statusText}用户 ${row.nickname || row.username} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await updateUserStatus({ id: row.id, status })
      ElMessage.success(`${statusText}用户成功`)
      fetchUserList()
    } catch (error) {
      console.error(`${statusText}用户失败`, error)
    }
  }).catch(() => {})
}

// 角色变更
const handleRoleChange = (row) => {
  roleDialog.visible = true
  roleDialog.userId = row.id
  roleDialog.currentRole = row.roleCode
  roleForm.id = row.id
  roleForm.roleCode = ''
}

// 提交角色变更
const submitRoleChange = async () => {
  if (!roleFormRef.value) return
  
  try {
    await roleFormRef.value.validate()
    
    // 检查是否与当前角色相同
    if (roleForm.roleCode === roleDialog.currentRole) {
      ElMessage.warning('新角色与当前角色相同，无需变更')
      return
    }
    
    await updateUserRole(roleForm)
    ElMessage.success('角色变更成功')
    
    roleDialog.visible = false
    fetchUserList()
  } catch (error) {
    console.error('角色变更失败', error)
  }
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除用户 ${row.nickname || row.username} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteUser(row.id)
      ElMessage.success('删除用户成功')
      fetchUserList()
    } catch (error) {
      console.error('删除用户失败', error)
    }
  }).catch(() => {})
}

// 分页处理
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  fetchUserList()
}

const handleCurrentChange = (current) => {
  queryParams.pageNum = current
  fetchUserList()
}

// 生命周期钩子
onMounted(() => {
  fetchUserList()
  fetchRoles()
})
</script>

<style lang="scss" scoped>
.user-management-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .page-title {
      font-size: 22px;
      font-weight: 600;
      color: #303133;
      margin: 0;
    }
  }
  
  .search-form {
    background-color: #f5f7fa;
    padding: 20px;
    border-radius: 12px;
    margin-bottom: 20px;

    :deep(.el-select) {
      width: 150px;
    }
  }
  
  .table-card {
    border-radius: 12px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  }
  
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
  
  :deep(.el-tag) {
    border-radius: 12px;
  }
  
  :deep(.el-card) {
    border-radius: 12px;
  }
  
  :deep(.el-button) {
    border-radius: 20px;
  }
  
  :deep(.el-input__wrapper) {
    border-radius: 20px;
  }
  
  :deep(.el-select .el-input__wrapper) {
    border-radius: 20px;
  }
  
  :deep(.el-dialog__header) {
    padding: 20px;
    margin: 0;
    border-bottom: 1px solid #f0f0f0;
    text-align: center;
  }
  
  :deep(.el-dialog__body) {
    padding: 30px 20px;
  }
  
  :deep(.el-dialog__footer) {
    padding: 10px 20px 20px;
    text-align: center;
  }
  
  :deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;
  }
}
</style> 